import cv2
import numpy

def myresize(srcimg,shrink_size):
    # srcimg = cv.imread(string, 1)
    height, width = srcimg.shape[:2]
    size = (int(width * shrink_size), int(height * shrink_size))
    shrink = cv2.resize(srcimg, size, interpolation=cv2.INTER_AREA)
    return shrink

#读取图像
image_l=cv2.imread("book2.jpg",1)
image_r=cv2.imread("book3.jpg",1)
# image_l=myresize(image_l,0.3)
# image_r=myresize(image_r,0.3)
# cv2.imshow("scr_l",image_l)
# cv2.imshow("scr_2",image_r)
#灰度转换
image_l_01=cv2.cvtColor(image_l,cv2.COLOR_BGR2GRAY)
image_r_01=cv2.cvtColor(image_r,cv2.COLOR_BGR2GRAY)
#sfit提取特征点
sift = cv2.xfeatures2d.SIFT_create()  # 不能用cv.SIFT(),xfeatures2d需要pip install opencv-contrib-python
kp1, des1 = sift.detectAndCompute(image_l_01, None)
kp2, des2 = sift.detectAndCompute(image_r_01, None)

# orb
# orb=cv2.ORB.create(500)# 不能用cv.SIFT(),xfeatures2d需要pip install opencv-contrib-python
# kp1, des1 = orb.detectAndCompute(image_l_01, None)
# kp2, des2 = orb.detectAndCompute(image_r_01, None)

# FLANN parameters
FLANN_INDEX_KDTREE = 0
index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 4)
search_params = dict(checks=40)

flann = cv2.FlannBasedMatcher(index_params,search_params)
matches = flann.knnMatch(des1,des2,k=2)
# # 蛮力匹配算法,有两个参数，距离度量(L2(default),L1)，是否交叉匹配(默认false)
# bf = cv2.BFMatcher()
# #返回k个最佳匹配
# matches = bf.knnMatch(des1, des2, k=2)
good = []
for m,n in matches:
     if m.distance < 0.61*n.distance:
        good.append(m)

draw_params = dict(matchColor = (0,255,0))
image_match=cv2.drawMatches(image_l_01,kp1,image_r_01,kp2,good,None,**draw_params)
cv2.imshow("match",image_match)
cv2.waitKey(0)
